package com.inspur.gs.sbssdl.sbssgl.sbtz.sbtz.back.sbsssbtz.validations;
import com.inspur.edp.bef.api.exceptions.BizMessageException;
import com.inspur.edp.bef.api.lcp.IStandardLcp;
import com.inspur.edp.bef.core.LcpUtil;
import com.inspur.edp.cef.api.message.*;
import com.inspur.edp.cef.entity.changeset.*;
import com.inspur.edp.bef.spi.action.validation.AbstractValidation;
import com.inspur.edp.bef.api.action.validation.IValidationContext;
import com.inspur.edp.cef.entity.condition.EntityFilter;
import com.inspur.edp.cef.entity.condition.FilterCondition;
import com.inspur.edp.cef.entity.entity.IEntityData;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.List;

@Log4j2
public class SbssSbtzValBeforeSave1MgrAction extends AbstractValidation {
	public SbssSbtzValBeforeSave1MgrAction(IValidationContext context, IChangeDetail change) {
		super(context,change);
	}
	@Override
	public void execute() {
		IEntityData data = getData();

		// 查询非当前ID，但是编号相同的数据
		IStandardLcp tzLcp = LcpUtil.getLcp("com.inspur.gs.sbssdl.sbssgl.sbtz.sbtz.back.SbssSbtz");

		if (data.getValue("sbbh") == null || data.getValue("sbbh").toString().isEmpty()){
			return;
		}

		EntityFilter filter = new EntityFilter();
		ArrayList<FilterCondition> list = new ArrayList<>(FilterCondition.builder()
				.andNotEqual("ID",data.getID())
				.andEqual("sbbh",data.getValue("sbbh").toString())
				.build()
		);

		filter.setFilterConditions(list);
		List<IEntityData> query = tzLcp.query(filter);

		// 如果存在，则抛出异常
		if(!query.isEmpty()){
			System.out.printf("ID:%s ; 设备编号:%s ; 冲突ID : %s ; \n 冲突信息 : %s",
					data.getID(),
					data.getValue("sbbh").toString(),
					query.get(0).getID(),
					query);
			IBizMessage text = getContext().createMessageWithLocation(MessageLevel.Error, "该编号设备已存在,检查该编号设备并重新输入!");
			throw new BizMessageException("BHYCZ001", text);
		}

	}
	private IEntityData getData() {
		return (IEntityData)super.getContext().getCurrentData();
	}
}